<template>
  <div class="zTree">
    <Unfold v-on="$listeners" :isStatFold="true">
      <!-- 左侧组名称列表 -->
      <template v-slot:tree-list>
        <div class="left box">
          <!-- header -->
          <div class="box-header bg-primary text-white text-weight-regular">
            <select-input ref="selectInput"
                          style="color: white"
                          :list="searchCondition"
                          :isLongth="false"
                          @search="inputSearch"
                          @search2="inputSearchLine"
                          :byLine="showLine && tab==='2'"
                          @clearSearchVal="clearSearchVal" />
          </div>
          <div class="flex" v-if="showLine">
            <div class="tab border-left" :class="{'tab-active': tab === '1'}" @click="tab='1'">按组织架构</div>
            <div class="tab border-right" :class="{'tab-active': tab === '2'}" @click="tab='2'">按调度线</div>
          </div>
          <q-scroll-area :thumb-style="thumbStyle"
                         style="height: 100%"
                         class="tree-content bg-white">
            <div>
              <q-tree class="col-12 col-sm-6"
                      :nodes="simple"
                      ref="multiple"
                      node-key="hash"
                      :tick-strategy="tickStrategy"
                      @update:ticked="onUpdateTicked"
                      :ticked.sync="ticked"
                      noNodesLabel="暂无数据.."
                      control-color="#999999"
                      style="padding-left: 20px; padding-right: 20px; font-size: 16px"
                      default-expand-all>
                <template v-slot:default-header="prop">
                  <div class="row items-center">
                    <div>{{setProplabel(prop.node)}}</div>
                    <q-tooltip>{{setProplabel(prop.node)}}</q-tooltip>
                  </div>
                </template>
              </q-tree>
            </div>
          </q-scroll-area>
          <!--  加载中 -->
          <!-- <q-inner-loading :showing="isShowTree">
            <q-spinner-gears size="50px"
                             color="primary" />
          </q-inner-loading> -->
        </div>
      </template>
      <!-- 右侧 card -->
      <template v-slot:content>
        <div class="right box">
          <slot></slot>
        </div>
      </template>
    </Unfold>
  </div>
</template>

<script>
import Unfold from 'src/components/unfold'
import SelectInput from 'src/components/select-input'
import { getMachineTree } from 'src/boot/program-v2/machine'
import { getDevicesByNumberName } from 'src/boot/plan/dispatch'
import { defaultSchemesClearer } from 'src/assets/js/util'
import _ from 'lodash'
import { mapMutations, mapGetters } from 'vuex'
import { getDispatchingLine } from '../../../boot/system/fixed-scheduling'

export default {
  name: 'zTree',
  components: {
    Unfold,
    SelectInput
  },
  props: {
    isSetDisabled: {
      type: Boolean,
      default: false
    },
    showLine: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      tab: '1', // 1按组织架构，2按调度线
      searchCondition: [
        { id: 'assetNumber', name: '设备编号' },
        { id: 'deviceName', name: '设备名称' }
      ],
      isShowTree: false,
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式,
      // 选择每项的value值
      ticked: [],
      tickStrategy: 'leaf',
      tickFirst: [],
      tickFirstData: [],
      simple: [],
      zTreeList: [],
      zTreeListLine: null,
      count: null, // 选中的索引值
      countArr: [], // 没被选中的元素
      isDisabled: false,
      lineObj: {}
    }
  },
  watch: {
    // wei dian ji取消disabled
    ticked (val) {
      if (val.length === 0 && this.tab === '1') {
        this.simple.map(v => {
          this.setDisabled(v, false)
        })
      }
    },
    tab (val) {
      if (val === '2') {
        if (this.zTreeListLine) {
          this.simple = this.zTreeListLine
          this.setTreeDataLineFirst()
        } else {
          this.getLineInfo()
        }
      } else {
        this.simple = this.zTreeList
        this.setTreeDataFirst()
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'ztreeData'])
  },
  methods: {
    setProplabel (node) {
      return node.assetNumber ? `${node.label}(${node.assetNumber})` : node.label
    },
    // 模糊查询
    inputSearch (item, searchVal) {
      this.ticked = []
      this.isDisabled = true
      this.getDevicesByNumberName(item.id, searchVal)
    },
    inputSearchLine (searchVal) {
      const keys = Object.keys(this.lineObj)
      const result = []
      keys.forEach(key => {
        if (key.toUpperCase().indexOf(searchVal.toUpperCase()) > -1) {
          result.push(this.lineObj[key])
        }
      })
      this.simple = result
    },
    // 清空搜索值
    clearSearchVal () {
      if (this.showLine && this.tab === '2') {
        this.simple = this.zTreeListLine
        this.ticked = []
      } else {
        this.isDisabled = false
        // this.getInfo()
        this.simple = this.zTreeList
        this.ticked = []
      }
    },
    // 点击多选框时触犯事件
    onUpdateTicked (val) {
      if (!this.isDisabled && this.isSetDisabled) {
        const singleSelect = this.getSelectData(val)
        this.$nextTick(() => {
          this.ticked = singleSelect
        })
      }
      if (this.isDisabled && this.isSetDisabled) {
        this.getDisList(val)
      }
      this.$emit('updateTicked', val)
    },
    getInfo () {
      this.isShowTree = true
      getMachineTree().then(res => {
        this.isShowTree = false
        this.$emit('initAllTreeData', res.data)
        let folder = defaultSchemesClearer.clear(res.data)
        this.simple = _.cloneDeep(folder)
        this.simple = this.isSetDisabled ? this.flatten(this.simple) : this.simple
        this.simple.map(v => {
          const item = v
          item.hash = v.hash
          this.deleteDefault(v)
          this.setDisabled(v, false)
        })
        // 暂存树的数据;当清空搜索条件时防止再次搜索数据
        this.zTreeList = _.cloneDeep(this.simple)
        this.countArr = _.cloneDeep(this.simple)
        this.setZtreeData(this.zTreeList)
      }).then(() => {
        // if (!this.isSetDisabled) {
        this.setTreeDataFirst()
        // }
      })
    },
    getLineInfo () {
      getDispatchingLine('').then(res => {
        const data = res.data
        const result = []
        const obj = {}
        let firstCanSelect = ''
        data.forEach(item => {
          const info = {
            hash: item.workshopId,
            label: item.workshopName,
            children: []
          }
          item.lines.forEach(line => {
            const detailData = {
              hash: line.id,
              devices: line.devices,
              workshopId: item.workshopId,
              label: line.dispatchingName + `(${line.devices ? line.devices.length : 0})`,
              disabled: line.statusCode === 0
            }
            if (!firstCanSelect && !detailData.disabled) {
              firstCanSelect = detailData.hash
            }
            info.children.push(detailData)
            obj[line.dispatchingName] = detailData
          })
          result.push(info)
        })
        this.lineObj = obj
        this.zTreeListLine = _.cloneDeep(result)
        this.simple = _.cloneDeep(result)
        this.setTreeDataLineFirst(firstCanSelect)
      })
    },
    // 扁平化处理数组
    flatten (ary) {
      return ary.reduce((pre, cur) => {
        if (cur.level === 1 && cur.leveldesc === '分厂' && cur.children) {
          // 车间(分厂)
          cur.children.map(v => {
            const item = v
            if (v.level === 2) {
              item.label = v.parentName !== '/' ? `${v.label}(${v.parentName})` : v.label
            }
          })
          pre.push(...cur.children)
        } else {
          pre.push(cur)
        }
        return pre
      }, [])
    },
    // 清空label === ’‘
    deleteDefault (arr) {
      if (arr.children && arr.label) {
        arr.children = arr.children.filter(v => v.label !== '')
        arr.children.map(v => this.deleteDefault(v))
      }
    },
    // 初始化树的开始数据
    setTreeDataFirst () {
      this.tickFirst = []
      this.tickFirstData = []
      const tick = this.simple[0]
      this.setChildren(tick)
      this.$nextTick(() => {
        this.ticked = this.tickFirst
        this.onUpdateTicked(this.ticked)
        this.$emit('initData', this.tickFirstData)
      })
    },
    setTreeDataLineFirst (firstCanSelect) {
      if (this.simple && firstCanSelect) {
        const ticked = [firstCanSelect]
        this.$nextTick(() => {
          this.ticked = ticked
          this.onUpdateTicked(this.ticked)
          this.$emit('initData', this.simple[0].children)
        })
      }
    },
    setChildren (val) {
      if (val.children) {
        val.children.map(v => {
          this.setChildren(v)
        })
        // this.tickFirst.push(...val.children.map(v => v.hash))
        // this.tickFirstData.push(...val.children.map(v => v))
      } else {
        this.tickFirst.push(val.hash)
        this.tickFirstData.push(val)
        return [val.hash]
      }
    },
    // 初始添加disable
    setDisabled (arr, isD) {
      if (arr.children && arr.label) {
        arr.disabled = isD
        arr.children.map(v => this.setDisabled(v, isD))
      } else {
        arr.disabled = isD
      }
    },
    getSelectData (val) {
      const select = _.cloneDeep(val).reverse()
      const result = []
      if (this.showLine && this.tab === '2') {
        if (select && select.length > 0) {
          result.push(select[0])
        }
        return result
      }
      if (select && select.length > 0) {
        const id = select[0].split('/')[0]
        select.some(item => {
          if (item.split('/')[0] === id) {
            result.push(item)
          } else {
            return true
          }
        })
      }
      return result
    },
    // 模糊查询, 过滤不可点击状态
    getDisList (val) {
      if (!_.isEmpty(val)) {
        const member = val[0]
        const obj = _.find(this.simple, v => v.id === member)
        this.simple.map(v => {
          v.disabled = v.workshopId !== obj.workshopId
        })
      }
    },
    // 根据设备id,名称查询
    getDevicesByNumberName (type, id) {
      const item =
        type === 'assetNumber' ? { assetNumber: id } : { deviceName: id }
      const params = {
        ...item,
        type,
        tenantId: this.userInfo.tenant_id
      }
      this.isShowTree = true
      return getDevicesByNumberName(params)
        .then(res => {
          this.isShowTree = false
          let folder = defaultSchemesClearer.clear(res.data)
          this.simple = folder.map(v => {
            const item = v
            item.hash = v.id
            item.disabled = false
            item.level = 5 // 搜索结果手动添加第五层级（用于判断是否为设备）
            item.label = item.deviceName
            return item
          })
        })
        .catch(() => {
          this.isShowTree = false
          this.simple = []
        })
    },
    ...mapMutations({
      'setZtreeData': 'SET_ZTREEDATA'
    })
  },
  mounted () {
    this.getInfo()
  }
}
</script>

<style scoped lang="stylus">

>>>.q-hoverable{
  &:hover{
    .q-focus-helper{
      color: #5f77fd
    }
  }
}
>>>.q-tree__node-header {
  margin: 0;
  padding: 0;
}
.zTree
  height 100%
  >>>.left-part
    margin-right 0
    z-index 10
  .box
    display flex
    flex-direction column
    width 100%
    min-width 250px
    border-radius 6px
    overflow hidden
    margin-top 10px
    height 98%
    .box-header
      flex 40px 0
      padding 5px 20px
      line-height 40px
      font-size 18px
      /deep/ .q-field--dense .q-field__control, .q-field--dense .q-field__marginal
        background-color #ffffff
    &.left
      border 1px solid #eee
      .box-content
        flex 1
        padding-bottom 20px
        .role-item
          padding-left 30px
          font-size 16px
          &.activated
            background #d0d6fb
            color $primary
    &.right
      margin-top -5px
      margin-bottom -5px
      height calc(100% + 10px)
</style>
<style lang="scss">
.tab{
  width: 50%;
  font-size: 16px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  cursor: pointer;
  background: #d3d3d3
}

.tab-active{
  color: $primary;
  background: #ffffff
}
:not(.tab-active).border-right{
  border-bottom-left-radius: 10px;
}
:not(.tab-active).border-left{
  border-bottom-right-radius: 10px;
}
.zTree {
  .q-tree__node-header-content {
    white-space: nowrap;
    &:hover {
      color: #5f77fd !important;
    }
  }
  .q-tree > .q-tree__node--child > .q-tree__node-header {
    padding-left: 21px;
  }
  // .q-tree__node {
    // padding: 0 0 3px 23px;
  // }
  .q-checkbox--dense .q-checkbox__bg {
    width: 16px;
    height: 16px;
    border: 1px solid rgba(153, 153, 153, 1);
    border-radius: 2px;
  }
  .q-tree__arrow,
  .q-tree__spinner {
    font-size: 14px;
    margin-top: -3px;
  }
  .q-tree__node-header {
    height: 48px;
    border-radius: 0px;
    border-bottom: 1px solid rgba(211, 211, 211, 1);
  }
  .q-tree__node-header-content{
    div{
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
